<template>
    <div class="swiper">
        <ul :style="{
            width: banners.length*100 + '%',
            left: left,
            transition: transition
        }" @touchstart="touchStart" @touchmove="touchMove" @touchend="touchEnd">
            <li v-for="(item, i) in banners" :style="{
                width: 100/banners.length + '%'
            }" :key="i">
                <img :src="item.picUrl" alt="">
            </li>
        </ul>
    </div>
</template>

<script>
let timer
export default {
    name: '',
    props: {
        banners: {
            type: Array,
            default: () => {
                return []
            }
        }
    },
    data() { 
        return {
            left: '-100%',
            transition: 'none',
            dir: 'left',
            startX: 0
        }
    },
    created() {
        setInterval(() => {
            this.touchEnd()
        }, 3000)
    },
    methods:{
        touchStart(e) {
            // console.log(e);
            this.startX = e.touches[0].pageX // 手指点下去的初始位置
        },
        touchMove(e) {
            // console.log(e);
            let temp = e.touches[0].pageX - this.startX
            if(temp > 0) {
                this.dir = 'right'
            } else {
                this.dir = 'left'
            }
        },
        touchEnd() {
            clearTimeout(timer)
            this.transition = 'left 0.5s linear'
            if(this.dir == 'left') {
                this.left = '-200%'
                timer = setTimeout(() => {
                    this.transition = 'none'
                    let item = this.banners.shift()
                    this.banners.push(item)
                    this.left = '-100%'
                }, 500)
            } else {
                this.left = "0"
                timer = setTimeout(() => {
                    this.transition = 'none'
                    let item = this.banners.pop()
                    this.banners.unshift(item)
                    this.left = '-100%'
                }, 500)
            }
        }
    },
}
</script>

<style scoped lang="scss">
.swiper {
    width: 100%;
    img {
        width: 100%;
    }
    ul {
        display: flex;
        position: relative;
        
    }
}
</style>